package com.module.overview.ui.cardHistoryDetails.provider

import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.utils.JsonUtils
import com.common.base.utils.ViewUtils
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.HeartRateVariabilityRepo
import com.module.ble.repo.SportRecordRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.widget.CandlestickChart
import com.module.overview.R
import java.util.Calendar

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/11
 *
 * 描述：体征-血氧饱和度卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSignsHrvCardProvider(mCalendar: CalendarDay?,
                             override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SIGNS_HRV,
                             override val layoutId: Int = R.layout.overview_signs_hrv_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = mCalendar?.toCalendar()?.timeInMillis?:0

    var tvAverageHrv: TextView? = null
    var tvLastTime: TextView? = null
    private var candlestickChart: CandlestickChart? = null
    var tvTheDayAverage: TextView? = null
    var tvTheDayScope: TextView? = null

    var lastResult :Number = -1

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        // 设置Y轴阶段
        candlestickChart?.setYAxisStages(
            floatArrayOf(40f, 110f, 180f), // 阶段分界点
        )

        getTheDayHrv()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvAverageHrv = viewHolder.getView(R.id.tvAverageHrv)
        tvLastTime = viewHolder.getView(R.id.tvLastTime)
        candlestickChart = viewHolder.getView(R.id.candlestickChart)
        tvTheDayAverage = viewHolder.getView(R.id.tvTheDayAverage)
        tvTheDayScope = viewHolder.getView(R.id.tvTheDayScope)

        // 设置触摸监听
        candlestickChart?.setOnBarTouchListener(object : CandlestickChart.OnBarTouchListener {

            override fun onBarTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
                // 处理触摸事件
//                Log.d("CandlestickChart", "触摸到柱子: 索引=$barIndex,触摸到: $timeLabel, 值: $minValue")
                tvAverageHrv?.text = "${if (minValue.toInt() <= 0) ViewUtils.getString(R.string.common_rail_unit) else minValue.toInt()}~${if (maxValue.toInt() <= 0) ViewUtils.getString(R.string.common_rail_unit) else maxValue.toInt()}"
                tvLastTime?.text = extStr
            }

            override fun onAverageLineTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
                tvAverageHrv?.text = if (lastResult.toInt() <= -1) ViewUtils.getString(R.string.common_rail_unit) else lastResult.toString()
                tvLastTime?.text = ViewUtils.getString(R.string.common_last_time_hint)
            }
        })
        super.onViewHolderCreated(viewHolder, viewType)
    }


    /**
     * 获取当天心率变异性
     */
    fun getTheDayHrv(){
        if (curTime <=0) return

        doOnIOThread {
            //当天心率变异性
            HeartRateVariabilityRepo.instance.findAllByDayWithHrv(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@let

                val listItStr = JsonUtils.toJson(originalListIt)

                // 创建48个时间区间块的CusChartData数组
                val stressListData = mutableListOf<CusChartData>()

                // 获取curTime当天的0点时间戳
                val calendar = Calendar.getInstance()
                calendar.timeInMillis = curTime
                calendar.set(Calendar.HOUR_OF_DAY, 0)
                calendar.set(Calendar.MINUTE, 0)
                calendar.set(Calendar.SECOND, 0)
                calendar.set(Calendar.MILLISECOND, 0)
                val startOfDay = calendar.timeInMillis

                for (index in 0 until 48) {
                    val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
                    val intervalStartTime = startOfDay + timeOffset
                    val intervalEndTime = startOfDay + timeOffset + (30 * 60 * 1000L) // 加30分钟作为结束时间

                    // 查找在当前时间区间内的心率数据
                    val dataInInterval = originalListIt.filter { oxyRateData ->
                        oxyRateData.createdTime in intervalStartTime until intervalEndTime
                    }

                    var extStr = ""

                    // 生成extStr，格式为"最小值~最大值"
                    var minValue = 0
                    var maxValue = 0

                    if (dataInInterval.isNotEmpty()) {
                        // 生成extStr，格式为"最小值~最大值"
                        minValue = dataInInterval.minOfOrNull { it.heartRateVariability }?:0
                        maxValue = dataInInterval.maxOfOrNull { it.heartRateVariability }?:0
                        extStr = "$minValue~$maxValue"
                    }
                    else {
//                        // 如果区间内没有数据，设置为0
//                        mValue = -1f
                        extStr = ""
                    }

                    stressListData.add(
                        CusChartData(
                            createdTime = intervalStartTime,
                            endTime = intervalEndTime,
                            mValue = maxValue.toFloat(),
                            minValue = minValue.toFloat(),
                            exStr = extStr,
                            dayNum = 0
                        )
                    )
                }

                val stressListDataStr = JsonUtils.toJson(stressListData)
                val minTemp = ((originalListIt.minOfOrNull { it.heartRateVariability } ?: 0f).toFloat())
                val maxTemp = ((originalListIt.maxOfOrNull { it.heartRateVariability } ?: 0f).toFloat())
                val theDayAverage = if (originalListIt.isNotEmpty()) {//当日平均
                    originalListIt.map { it.heartRateVariability }.average().toInt().toString()
                } else {
                    ViewUtils.getString(R.string.common_rail_unit)
                }
                lastResult = originalListIt
                    .filter { it.heartRateVariability > 0 }  // 过滤 heartRateVariability 大于 0 的数据
                    .maxByOrNull { it.createdTime }          // 获取 createdTime 最大的数据
                    ?.heartRateVariability                   // 取出 heartRateVariability 值
                    ?: -1                                    // 如果没有符合条件的数据，返回 -1

                doOnUiThread {

                    tvAverageHrv?.text = if (lastResult.toInt() <= -1) ViewUtils.getString(R.string.common_rail_unit) else lastResult.toString()

                    tvTheDayAverage?.text = theDayAverage
                    tvTheDayScope?.text = "${minTemp.toInt()}~${maxTemp.toInt()}"

                    // 设置Y轴阶段
                    candlestickChart?.setYAxisStages(
                        floatArrayOf(if(minTemp-10f <=0) 0f else minTemp-10f, ((maxTemp-minTemp)/2).toInt()+minTemp, maxTemp+10f), // 阶段分界点
                    )
                    // 通知图表更新数据
                    candlestickChart?.setData(stressListData)
                }

                getTheDaySportsData(stressListData)
            }
        }
    }


    /**
     * 获取当天运动信息
     */
    fun getTheDaySportsData(stressListData : MutableList<CusChartData>){
        doOnIOThread {
            SportRecordRepo.instance.findAllByDay(TimeUtils.getTimeDateLong())?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@let
//                val listItStr = JsonUtils.toJson(originalListIt)

                // 遍历运动数据记录数组
                originalListIt.forEach { beanIt->
                    // 遍历stressListData中的每条数据
                    for (i in stressListData.indices) {
                        val stressBeanIt = stressListData[i]
                        // 判断stressListData每天数据的createdTime时间戳是否在beanIt的startTs和endTs范围内
                        if (stressBeanIt.createdTime in beanIt.startTs until beanIt.endTs) {
                            // 如果在范围内，将该条stressBeanIt.selectBg设置为true
                            stressListData[i] = stressBeanIt.copy(selectBg = true)
                        }
                    }
                }

                doOnUiThread {
                    // 通知图表更新数据
                    candlestickChart?.setData(stressListData)
                }
            }
        }
    }
}